package cn.butcher.controller;

import cn.butcher.mapper.RouterMapper;
import cn.butcher.vo.CounselorVo;
import cn.butcher.vo.CourseVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 路由跳转
 */
@Controller
public class RouterController {

    @Autowired
    RouterMapper routerMapper;

//    @Autowired
//    UserMapper userMapper;

    @RequestMapping({"/", "index", "index.html"})
    public String toIndex() {
        return "index";
    }

    @RequestMapping("/login")
    public String login(String username, String password, Model model, HttpSession session) {
        // 上次我们使用shiro完成了登录
        // 这次完成授权，也就是不同的角色登录，前端显示的页面不一样
        // 还有将当前用户的状态存入session
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
            session.setAttribute("id", username);
            return "redirect:index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg", "学号不存在");
            return "redirect:login";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("msg", "密码错误");
            return "redirect:login";
        } catch (AuthenticationException e) {
            model.addAttribute("msg", "学号不存在");
            return "redirect:login";
        }

    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        // 使用shiro登出
        // 以前我们是使用 session 去管理我们的会话，如果要登出，就需要获取session，然后销毁我们的session
        return "login";
    }

    @RequestMapping("/student/apply")
    public String toApply(Model model, HttpSession session) {
        Integer stId = (Integer) session.getAttribute("stId");

        List<CourseVo> courseVoList = routerMapper.getCourse(1800500926);
        model.addAttribute("courseVoList", courseVoList);

        List<CounselorVo> counselorList = routerMapper.getCounselor(1800500926);
        model.addAttribute("counselorList", counselorList);

        return "page/student-apply";
    }


}
